package net.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UDPPoke
{
	private int bufferSize;
	private DatagramSocket socket;
	private DatagramPacket outgoing;
	public UDPPoke(InetAddress host,int port,int bufferSize,int timeout) throws SocketException
	{
		outgoing = new DatagramPacket(new byte[1],1 ,host,port);
		this.bufferSize = bufferSize;
		socket = new DatagramSocket(0);
		socket.connect(host,port);
		socket.setSoTimeout(timeout);
		
	}
	public UDPPoke(InetAddress host,int port,int bufferSize) throws SocketException
	{
		this(host, port, bufferSize, 30000);
	}
	public UDPPoke(InetAddress host,int port) throws SocketException
	{
		this(host,port,8192,30000);
	}
	public byte[] poke() throws IOException 
	{
		byte[] response = null;
		try
		{
			socket.send(outgoing);
			DatagramPacket incoming = new DatagramPacket(new byte[bufferSize], bufferSize);
			socket.receive(incoming);
			int numBytes = incoming.getLength();
			response = new byte[numBytes];
		}
		catch (Exception e)
		{
		}
		return response;
	}
	public static void main(String[] args)
	{
		InetAddress host = null;
		int port = 0;
		try
		{
			host = InetAddress.getByName("localhost");
			port = 9;
		}
		catch (Exception e)
		{
		}
		try
		{
			UDPPoke poker = new UDPPoke(host, port);
			byte[] response = poker.poke();
			if(response == null)
			{
				return;
			}
			String result = "";
			try
			{
				result = new String(response,"ASCII");
			}
			catch (Exception e)
			{
			}
			System.out.println(result);
		}
		catch (Exception e)
		{
		}
	}
}
